package cn.iocoder.yudao.module.ao.controller.admin.classlocation;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import lombok.extern.slf4j.Slf4j;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.ao.controller.admin.classlocation.vo.*;
import cn.iocoder.yudao.module.ao.dal.dataobject.classlocation.ClassLocationDO;
import cn.iocoder.yudao.module.ao.service.classlocation.ClassLocationService;

@Tag(name = "管理后台 - 上课场地信息")
@RestController
@RequestMapping("/ao/class-location")
@Validated
@Slf4j
public class ClassLocationController {

    @Resource
    private ClassLocationService classLocationService;

    @PostMapping("/create")
    @Operation(summary = "创建上课场地信息")
    @PreAuthorize("@ss.hasPermission('ao:class-location:create')")
    public CommonResult<Long> createClassLocation(@Valid @RequestBody ClassLocationSaveReqVO createReqVO) {
        return success(classLocationService.createClassLocation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新上课场地信息")
    @PreAuthorize("@ss.hasPermission('ao:class-location:update')")
    public CommonResult<Boolean> updateClassLocation(@Valid @RequestBody ClassLocationSaveReqVO updateReqVO) {
        classLocationService.updateClassLocation(updateReqVO);
        return success(true);
    }

    // 删除功能已移除，防止误删重要的上课场地基础数据
    // @DeleteMapping("/delete")
    // @Operation(summary = "删除上课场地信息")
    // @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('ao:class-location:delete')")
    // public CommonResult<Boolean> deleteClassLocation(@RequestParam("id") Long id) {
    //     classLocationService.deleteClassLocation(id);
    //     return success(true);
    // }

    // @DeleteMapping("/delete-list")
    // @Parameter(name = "ids", description = "编号", required = true)
    // @Operation(summary = "批量删除上课场地信息")
    // @PreAuthorize("@ss.hasPermission('ao:class-location:delete')")
    // public CommonResult<Boolean> deleteClassLocationList(@RequestParam("ids") List<Long> ids) {
    //     classLocationService.deleteClassLocationListByIds(ids);
    //     return success(true);
    // }

    @GetMapping("/get")
    @Operation(summary = "获得上课场地信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ao:class-location:query')")
    public CommonResult<ClassLocationRespVO> getClassLocation(@RequestParam("id") Long id) {
        ClassLocationDO classLocation = classLocationService.getClassLocation(id);
        return success(BeanUtils.toBean(classLocation, ClassLocationRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得上课场地信息分页")
    @PreAuthorize("@ss.hasPermission('ao:class-location:query')")
    public CommonResult<PageResult<ClassLocationRespVO>> getClassLocationPage(@Valid ClassLocationPageReqVO pageReqVO) {
        PageResult<ClassLocationDO> pageResult = classLocationService.getClassLocationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ClassLocationRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出上课场地信息 Excel")
    @PreAuthorize("@ss.hasPermission('ao:class-location:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportClassLocationExcel(@Valid ClassLocationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ClassLocationDO> list = classLocationService.getClassLocationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "上课场地信息.xls", "数据", ClassLocationRespVO.class,
                        BeanUtils.toBean(list, ClassLocationRespVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入上课场地信息模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<ClassLocationImportExcelVO> list = Arrays.asList(
                ClassLocationImportExcelVO.builder()
                        .locationName("笃志楼机房9")
                        .buildingName("笃志楼")
                        .floor(3)
                        .classroomCapacity(50)
                        .build(),
                ClassLocationImportExcelVO.builder()
                        .locationName("博学楼实训室1")
                        .buildingName("博学楼")
                        .floor(2)
                        .classroomCapacity(40)
                        .build()
        );
        // 输出
        ExcelUtils.write(response, "上课场地信息导入模板.xls", "上课场地信息列表", ClassLocationImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入上课场地信息")
    // @PreAuthorize("@ss.hasPermission('ao:class-location:import')")  // 临时注释权限检查
    @Parameter(name = "file", description = "Excel 文件", required = true)
    @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    public CommonResult<ClassLocationImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        log.info("开始导入上课场地信息，文件名: {}, 文件大小: {} bytes, 支持更新: {}",
                file.getOriginalFilename(), file.getSize(), updateSupport);

        List<ClassLocationImportExcelVO> list = ExcelUtils.read(file, ClassLocationImportExcelVO.class);
        log.info("Excel解析完成，解析到 {} 条数据", list.size());

        // 打印前几条数据用于调试
        for (int i = 0; i < Math.min(3, list.size()); i++) {
            ClassLocationImportExcelVO item = list.get(i);
            log.info("第 {} 条数据: locationName={}, buildingName={}, floor={}, classroomCapacity={}",
                i + 1, item.getLocationName(), item.getBuildingName(), item.getFloor(), item.getClassroomCapacity());
        }

        return success(classLocationService.importClassLocationList(list, updateSupport));
    }

}